
// Loads pages for our app

var jsFiles = [ '1.js', '2.js', '3.js', '4.js' ] // the names will be replaced by builder

function Loader( contentElId, onloadCallback )
{	
	// contentId is <id> of section where to load

	this._contentElId = contentElId;

	this._lastPageN = null; // last loaded page

	this._isLoading = false;

	this._finishLoading = function()
	{
		this._isLoading = false;
	};
	
	// n is a section_number, data_ is object of params
	this.load = function( n, data_ )
	{
		if( !this._isLoading )
		{		
			this._isLoading = true;
	
			// remove previous <script> not to conflict with the new one
			if( this._lastPageN != null )
			{
				var lastUrl = format( urlTemplate, this._lastPageN );
				$( format( '[src={0}]', lastUrl ) ).remove();
			}
	
			// load new script
        
        	var jsUrl = format( "/static/js/{0}", jsFiles[ n - 1 ] );
        	var htmlUrl = format( "/{0}/", n );

        	var data = data_;
        	if( data == null )
        	{
        		data = {};
        	}

        	data[ 'sid' ] = sid;
        	data[ 'oid' ] = userId;

			var this_ = this;

			$.when(
				$.ajax(
					{
						url: jsUrl,
						dataType: "script"
					}
				),
				$.ajax(
					{
						url: htmlUrl,
						dataType: "html",
						data: data
					}
				)
			).then(
				function( data1, data2 )
				{
					$( '#' + contentElId ).html( data2[ 0 ] );
					this_._finishLoading();
					onloadCallback();
				},
				function( jqXHR, textStatus, errorThrown )
				{
					this_._finishLoading();
				}
			);
	
		}
	};
}

